import json
from typing import Any, Optional
from redis import Redis
from functools import wraps

from ..core.config import settings

_redis_client: Optional[Redis] = None

def get_redis_connection() -> Redis:
    """
    获取Redis连接（单例模式）
    """
    global _redis_client
    if _redis_client is None:
        _redis_client = Redis(
            host=settings.REDIS_HOST,
            port=settings.REDIS_PORT,
            db=settings.REDIS_DB,
            password=settings.REDIS_PASSWORD,
            decode_responses=True
        )
    return _redis_client

def cache(ttl_seconds: int = 60):
    """
    缓存装饰器，用于缓存函数结果
    """
    def decorator(func):
        @wraps(func)
        async def wrapper(*args, **kwargs):
            # 生成缓存键
            cache_key = f"cache:{func.__name__}:{hash(str(args) + str(kwargs))}"

            # 尝试从缓存获取
            redis = get_redis_connection()
            cached_result = redis.get(cache_key)

            if cached_result:
                return json.loads(cached_result)

            # 执行原始函数
            result = await func(*args, **kwargs)

            # 缓存结果
            redis.setex(cache_key, ttl_seconds, json.dumps(result))

            return result
        return wrapper
    return decorator

def invalidate_cache(pattern: str):
    """
    使指定模式的缓存失效
    """
    redis = get_redis_connection()
    keys = redis.keys(pattern)
    if keys:
        redis.delete(*keys)